package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {
    @Autowired
    private CacheService cacheService;

    //文章收藏
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        ApCollection one = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getArticleId, dto.getEntryId()));
        //cacheService.lRemove(user.getId() + "collection" + dto.getEntryId(), 0, 0 + "");
        if (dto.getOperation() == 0) {
            if (one == null) {
                ApCollection apCollection = new ApCollection();
                apCollection.setCollectionTime(new Date());
                apCollection.setArticleId(dto.getEntryId());
                apCollection.setType(dto.getType());
                apCollection.setPublishTime(new Date());
                apCollection.setEntryId(user.getId());
                save(apCollection);
                cacheService.lLeftPush(user.getId() + "collection", dto.getOperation() + "");
            } else {
                one.setPublishTime(new Date());
                updateById(one);
                cacheService.lLeftPush(user.getId() + "collection", dto.getOperation() + "");
            }
        } else {
            if (one != null) {
                removeById(one.getId());
            }
            cacheService.lRightPop(user.getId() + "collection");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
